<?php

namespace app\admin\controller\qingdongwms\statistics;

use app\admin\controller\qingdongwms\Base;
use addons\qingdongwms\model\Contract;
use addons\qingdongwms\model\Customer as CustomerModel;
use addons\qingdongwms\model\Event;
use addons\qingdongwms\model\Quote;
use addons\qingdongwms\model\Staff;
use addons\qingdongwms\model\StaffSignIn;
use addons\qingdongwms\model\Receivables;
use addons\qingdongwms\model\Field;
use app\admin\model\AuthGroup;
use think\Exception;

/**
 * 客户分析
 *
 * @icon fa fa-circle-o
 */
class Customer extends Base
{

    /**
     * PartyBuilding模型对象
     * @var \addons\qingdongwms\model\Customer
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new CustomerModel();
        $this->assign('typeList', [0 => '请选择', 1 => '部门', 2 => '员工']);
        try {
            \think\Db::execute("SET @@sql_mode='';");
        } catch (Exception $e) {

        }
    }

    // 新客分析
    public function new()
    {
        list($where, $times, $row) = $this->getWhere();//获取where
        list($result, $table) = $this->getCustomerList($where, $times);
        $this->view->assign([
            'result' => $result,
            'table' => $table,
            'row' => $row
        ]);
        $this->assignconfig('result', $result);
        $this->assignconfig('ids', $row['ids']);
        return $this->view->fetch();
    }

    // 客户成交

    public function getWhere($type = 0)
    {
        $beforeDays = strtotime(date('Y-m-d', strtotime('-30 day', time())));
        $times = [$beforeDays, time()];

        $this->request->filter(['strip_tags']);
        $row['type_id'] = 0;
        $row['ids'] = 0;
        $where = [];
        if ($this->request->get()) {
            $params = $this->request->get('row/a');
            if (isset($params['times']) && !empty($params['times'])) {
                $timesArr = explode('-', $params['times']);
                if (count($timesArr) < 5) {
                    $this->error('时间格式错误');
                }
                $times[0] = $timesArr[0] . '-' . $timesArr[1] . '-' . $timesArr[2];
                $times[1] = $timesArr[3] . '-' . $timesArr[4] . '-' . $timesArr[5];
                $times = [strtotime($times[0]), strtotime($times[1]) + 86400];
            }
            $row['type_id'] = $params['type_id'];
            $row['ids'] = $params['ids'] ?? 0;
            if ($params['type_id'] == 1 && $params['ids']) {
                $l_ids = Staff::getOneGroupStaffIds($params['ids']);
                if ($type == 1) {
                    $where['staff_id'] = ['in', $l_ids];
                } else {
                    $where['create_staff_id'] = ['in', $l_ids];
                }
            } elseif ($params['type_id'] == 2 && $params['ids']) {
                if ($type == 1) {
                    $where['staff_id'] = $params['ids'];
                } else {
                    $where['create_staff_id'] = $params['ids'];
                }

            }
        }
        $row['times'] = implode(' - ', [date("Y-m-d", $times[0]), date("Y-m-d", $times[1])]);
        $where['createtime'] = ['between', $times];
        return [$where, $times, $row];
    }

    //跟进分析

    public function getCustomerList($where, $times)
    {
        // 图标
        $result = CustomerModel::where($where)
            ->field('count(*) as count,FROM_UNIXTIME(createtime,"%Y-%m-%d") as time')
            ->group('time')->select();
        $trade_result = CustomerModel::where($where)->where(['contract_status' => 1])
            ->field('count(*) as count,trade_date')
            ->group('trade_date')->select();
        $addCount = [];
        foreach ($result as $v) {
            $addCount[$v['time']] = $v['count'];
        }
        $tradeCount = [];
        foreach ($trade_result as $v) {
            $tradeCount[$v['trade_date']] = $v['count'];
        }
        $dateList = getDateList($times[0], $times[1]);
        $result = [];

        foreach ($dateList as $date) {
            $result['date'][] = $date;
            $result['add_count'][] = $addCount[$date] ?? 0;
            $result['trade_count'][] = $tradeCount[$date] ?? 0;

        }
        // 员工区分
        $staffAdd = CustomerModel::where($where)
            ->field('count(*) as count,create_staff_id')
            ->group('create_staff_id')->select();
        $staffBook = CustomerModel::where($where)->where(['contract_status' => 1])
            ->field('count(*) as count,create_staff_id')
            ->group('create_staff_id')->select();

        $staffIds = array_unique(array_merge(array_column($staffAdd, 'create_staff_id'), array_column($staffBook, 'create_staff_id')));
        $staffList = Staff::where('id', 'in', $staffIds)->column('name', 'id');
        $staffAdd = $this->getArr($staffAdd, 'create_staff_id');
        $staffBook = $this->getArr($staffBook, 'create_staff_id');
        $totalAdd = array_sum($staffAdd);
        $totalBook = array_sum($staffBook);
        $table[] = [
            'name' => '总计',
            'add' => $totalAdd,
            'book' => $totalBook,
        ];
        foreach ($staffList as $key => $item) {
            $table[] = [
                'name' => $staffList[$key],
                'add' => isset($staffAdd[$key]) ? $staffAdd[$key] : 0,
                'book' => isset($staffBook[$key]) ? $staffBook[$key] : 0,
            ];
        }
        return [$result, $table];
    }

    // 筛选条件

    public function getArr($data, $key)
    {
        $tradeCount = [];
        foreach ($data as $v) {
            $tradeCount[$v[$key]] = $v['count'];
        }
        return $tradeCount;
    }

    //筛选条件

    public function deal()
    {
        list($where, $times, $row) = $this->getWhere();//获取where
        //到访
        $toWhere = array_merge($where, ['process' => 2]);
        $toResult = Event::where($toWhere)->field('count(*) as count,create_staff_id')->group('relation_id')->select();
        // 报价
        $quoteWhere = array_merge($where, ['check_status' => 2]);
        $quoteResult = Quote::where($quoteWhere)->field('count(*) as count,create_staff_id')->group('customer_id')->select();
        // 合同生效
        $contractWhere = array_merge($where, ['check_status' => 2]);
        $contractResult = Contract::where($contractWhere)->field('count(*) as count,create_staff_id')->group('customer_id')->select();

        // 表格
        $staffIds = array_unique(array_merge(array_column($toResult, 'create_staff_id'), array_column($quoteResult, 'create_staff_id'), array_column($contractResult, 'create_staff_id')));
        $staffList = Staff::where('id', 'in', $staffIds)->column('name', 'id');

        $toResult = $this->getArr($toResult, 'create_staff_id');
        $quoteResult = $this->getArr($quoteResult, 'create_staff_id');
        $contractResult = $this->getArr($contractResult, 'create_staff_id');

        $totalTo = array_sum($toResult);
        $totalQuote = array_sum($quoteResult);
        $totalContract = array_sum($contractResult);

        $table[] = [
            'name' => '总计',
            'to' => $totalTo,
            'quote' => $totalQuote,
            'contract' => $totalContract,
        ];
        $result = [
            ['value' => $totalTo, 'name' => '到访'],
            ['value' => $totalQuote, 'name' => '报价'],
            ['value' => $totalContract, 'name' => '合同'],
        ];

        foreach ($staffList as $key => $item) {
            $table[] = [
                'name' => $staffList[$key],
                'to' => isset($toResult[$key]) ? $toResult[$key] : 0,
                'quote' => isset($quoteResult[$key]) ? $quoteResult[$key] : 0,
                'contract' => isset($contractResult[$key]) ? $contractResult[$key] : 0,
            ];
        }
        $this->view->assign([
            'result' => $result,
            'table' => $table,
            'row' => $row
        ]);
        $this->assignconfig('result', $result);
        $this->assignconfig('ids', $row['ids']);
        return $this->view->fetch();
    }

    //筛选条件

    public function follow()
    {
        list($where, $times, $row) = $this->getWhere(1);//获取where
        list($result, $table) = $this->getFollowList($where, $times);
        $this->view->assign([
            'result' => $result,
            'table' => $table,
            'row' => $row
        ]);
        $this->assignconfig('result', $result);
        $this->assignconfig('ids', $row['ids']);
        return $this->view->fetch();
    }

    //筛选条件
    public function getFollowList($where, $times)
    {
        // 员工跟进次数
        $result = StaffSignIn::where($where)
            ->field('count(*) as count,FROM_UNIXTIME(createtime,"%Y-%m-%d") as time')
            ->group('time,customer_id')->select();

        // 唠嗑跟进次数
        $trade_result = StaffSignIn::where($where)->where(['customer_status' => 1])//成交
        ->field('count(*) as count,FROM_UNIXTIME(createtime,"%Y-%m-%d") as time')
            ->group('time,customer_id')->select();

        $addCount = $this->getArr($result, 'time');
        $tradeCount = $this->getArr($trade_result, 'time');
        $dateList = getDateList($times[0], $times[1]);
        $result = [];
        foreach ($dateList as $date) {
            $result['date'][] = $date;
            $result['add_count'][] = $addCount[$date] ?? 0;
            $result['trade_count'][] = $tradeCount[$date] ?? 0;
        }
        // 表格跟进次数
        $tableTimes = StaffSignIn::where($where)
            ->field('count(*) as count,FROM_UNIXTIME(createtime,"%Y-%m-%d") as time,staff_id')
            ->group('staff_id,time')->select();
        // 跟进客户数
        $tablePeople = StaffSignIn::where($where)->where(['customer_status' => 1])//成交
        ->field('count(*) as count,FROM_UNIXTIME(createtime,"%Y-%m-%d") as time,staff_id')
            ->group('staff_id,customer_id')->select();
        $staffIds = array_unique(array_merge(array_column($tableTimes, 'staff_id'), array_column($tablePeople, 'staff_id')));
        $staffList = Staff::where('id', 'in', $staffIds)->column('name', 'id');
        $tableTimes = $this->getArr($tableTimes, 'staff_id');
        $tablePeople = $this->getArr($tablePeople, 'staff_id');
        $totalAdd = array_sum($tableTimes);
        $totalBook = array_sum($tablePeople);
        $table[] = [
            'name' => '总计',
            'add' => $totalAdd,
            'book' => $totalBook,
        ];
        foreach ($staffList as $key => $item) {
            $table[] = [
                'name' => $staffList[$key],
                'add' => isset($tableTimes[$key]) ? $tableTimes[$key] : 0,// 跟进次数
                'book' => isset($tablePeople[$key]) ? $tablePeople[$key] : 0,// 跟进客户数
            ];
        }

        return [$result, $table];
    }

    //筛选条件
    public function staffes()
    {
        if ($this->request->isPost()) {
            $type_id = input('typeid');
            $params = [];
            if ($type_id == 1) {
                $model = new AuthGroup();
                $groups = $model->where($params)->field('id,name')->select();
                $list = [];
                foreach ($groups as $v) {
                    $list[$v['id']] = $v['name'];
                }
            } else {
                $model = new Staff();
                $params['status'] = 1;

                $list = $model->where($params)->column('name', 'id');
            }
            return json($list);
        }
    }

    /**
     * 客户总量分析
     */
    public function index()
    {
        $time = strtotime(date('Y-m', strtotime('-1 year')));
        $auth = Staff::getMyStaffIds();
        $staff_id = implode(',', $auth);  //权限
        //新增客户数
        $customers = CustomerModel::where([
            'createtime' => [
                'egt',
                $time
            ],
            'owner_staff_id' => ['in', $staff_id]
        ])->field("FROM_UNIXTIME(createtime,'%Y-%m') as ctime,count(*) as c")->group('ctime')->select();

        $select = [];
        foreach ($customers as $v) {
            $select[$v['ctime']] = $v['c'];
        }
        //已成交客户数
        $usecustomers = CustomerModel::where([
            'owner_staff_id' => ['in', $staff_id],
            'createtime' => [
                'egt',
                $time
            ],
            'contract_status' => 1
        ])->field("FROM_UNIXTIME(createtime,'%Y-%m') as ctime,count(*) as c")->group('ctime')->select();

        $useselect = [];
        foreach ($usecustomers as $v) {
            $useselect[$v['ctime']] = $v['c'];
        }

        $toMonthTime = strtotime(date('Y-m'));
        $typedata = [];
        for ($time; $time <= $toMonthTime; $time = strtotime('+1 month', $time)) {

            $typedata['date'][] = date('Y-m', $time);
            $typedata['num'][] = $select[date('Y-m', $time)] ?? 0;
            $typedata['use'][] = $useselect[date('Y-m', $time)] ?? 0;

        }
        $where['status'] = 1;
        $staff = Staff::where($where)->field('id,name')->select();
        $customInfo = [];
        foreach ($staff as $k => $v) {
            $customInfo[$k]['name'] = $v['name'];
            //新增客户数
            $addcustomer = CustomerModel::where(array('owner_staff_id' => $v['id']))->count();
            $customInfo[$k]['addcustomer'] = $addcustomer;
            //成交客户数
            $usecustomer = CustomerModel::where(array('owner_staff_id' => $v['id'], 'contract_status' => 1))->count();
            $customInfo[$k]['usecustomer'] = $usecustomer;
            //客户成交率(%)
            $customInfo[$k]['userate'] = $addcustomer ? sprintf("%.2f", $usecustomer / $addcustomer) : 0;
            //合同总金额
            $contractMoney = Contract::where(array('owner_staff_id' => $v['id'], 'check_status' => 2))->sum('money');
            $customInfo[$k]['contractMoney'] = $contractMoney;
            //回款金额
            $reciveMoney = Receivables::where(array('owner_staff_id' => $v['id'], 'check_status' => 2))->sum('money');
            $customInfo[$k]['reciveMoney'] = $reciveMoney;
            //未回款金额
            $customInfo[$k]['noreciveMoney'] = $contractMoney - $reciveMoney;
            //回款完成率
            $customInfo[$k]['ratereciveMoney'] = $contractMoney ? sprintf("%.2f", $reciveMoney / $contractMoney) : 0;
        }


        $this->view->assign([
            'customerdata' => $typedata,
            'customInfo' => $customInfo
        ]);

        return $this->view->fetch();
    }

    /**
     * 客户跟进次数分析
     */
    public function record()
    {

        $time = strtotime(date('Y-m', strtotime('-1 year')));
        $auth = Staff::getMyStaffIds();
        $staff_id = implode(',', $auth);  //权限修改
        //跟进客户数
        $customers = StaffSignIn::where([
            'staff_id' => ['in', $staff_id],
            'relation_type' => 0,
            'createtime' => [
                'egt',
                $time
            ]
        ])->field("FROM_UNIXTIME(createtime,'%Y-%m') as ctime,relation_id,count('*') as c")->group('relation_id,ctime')->select();

        $select = [];
        foreach ($customers as $v) {
            $select[$v['ctime']] = $v['c'];
        }
        //跟进次数
        $usecustomers = StaffSignIn::where([
            'staff_id' => ['in', $staff_id],
            'relation_type' => 0,
            'createtime' => [
                'egt',
                $time
            ]
        ])->field("FROM_UNIXTIME(createtime,'%Y-%m') as ctime,count(*) as c")->group('ctime')->select();

        $useselect = [];
        foreach ($usecustomers as $v) {
            $useselect[$v['ctime']] = $v['c'];
        }

        $toMonthTime = strtotime(date('Y-m'));
        $typedata = [];
        for ($time; $time <= $toMonthTime; $time = strtotime('+1 month', $time)) {

            $typedata['date'][] = date('Y-m', $time);
            $typedata['num'][] = $select[date('Y-m', $time)] ?? 0;
            $typedata['use'][] = $useselect[date('Y-m', $time)] ?? 0;

        }
        $where['status'] = 1;
        $staff = Staff::where($where)->field('id,name')->select();
        $customInfo = [];
        foreach ($staff as $k => $v) {
            $customInfo[$k]['name'] = $v['name'];
            //跟进客户数
            $addcustomer = StaffSignIn::where(array('staff_id' => $v['id'], 'relation_type' => 0))->group('relation_id')->count();
            $customInfo[$k]['addcustomer'] = $addcustomer;
            //跟进次数
            $usecustomer = StaffSignIn::where(array('staff_id' => $v['id'], 'relation_type' => 0))->count();
            $customInfo[$k]['usecustomer'] = $usecustomer;
        }


        $this->view->assign([
            'customerdata' => $typedata,
            'customInfo' => $customInfo
        ]);

        return $this->view->fetch();
    }

    /**
     * 客户跟进方式分析
     */
    public function recordtype()
    {
        //客户来源统计
        $time = strtotime(date('Y-m', strtotime('-1 year')));
        $auth = Staff::getMyStaffIds();
        $staff_id = implode(',', $auth);  //权限修改
        $sources = Field::getField('客户来源');
        $customers = CustomerModel::where([
            'owner_staff_id' => ['in', $staff_id],
            'createtime' => [
                'egt',
                $time
            ]
        ])->field("FROM_UNIXTIME(createtime,'%Y-%m') as ctime,source,count(*) as c")->group('source,ctime')->select();
        $select = [];
        foreach ($customers as $v) {
            $select[$v['source']][$v['ctime']] = $v['c'];
        }
        $toMonthTime = strtotime(date('Y-m'));
        $sourcedata = ['客户来源' => ['客户来源']];
        for ($time; $time <= $toMonthTime; $time = strtotime('+1 month', $time)) {
            $sourcedata['客户来源'][] = date('Y-m', $time);
            foreach ($sources as $v) {
                if (empty($sourcedata[$v])) {
                    $sourcedata[$v][] = $v;
                }
                $sourcedata[$v][] = intval($select[$v][date('Y-m', $time)] ?? 0);
            }
        }

        $this->view->assign([
            'customerdata' => array_values($sourcedata),
        ]);
        return $this->view->fetch();
    }


}
